const nodemailer = require('nodemailer');
const emailConfig = require('../config/emailConfig');

// 创建邮件传输器
const transporter = nodemailer.createTransport(emailConfig.qq);

// 存储验证码（实际项目中应该使用Redis）
const verificationCodes = new Map();

class EmailService {
    // 生成验证码
    static generateCode() {
        return Math.floor(100000 + Math.random() * 900000).toString();
    }

    // 发送验证码
    static async sendVerificationCode(email) {
        const code = this.generateCode();
        const mailOptions = {
            from: emailConfig.qq.auth.user,
            to: email,
            subject: '注册验证码',
            text: `您的验证码是：${code}，${emailConfig.codeExpiry}分钟内有效。`
        };

        try {
            await transporter.sendMail(mailOptions);
            // 保存验证码和过期时间
            verificationCodes.set(email, {
                code,
                expires: Date.now() + emailConfig.codeExpiry * 60 * 1000
            });
            return true;
        } catch (error) {
            throw new Error('验证码发送失败');
        }
    }

    // 验证验证码
    static verifyCode(email, code) {
        const verification = verificationCodes.get(email);
        if (!verification) {
            return false;
        }

        if (Date.now() > verification.expires) {
            verificationCodes.delete(email);
            return false;
        }

        if (verification.code === code) {
            verificationCodes.delete(email);
            return true;
        }

        return false;
    }
}

module.exports = EmailService; 